<template>
  <div style="padding-top: 5px;padding-bottom: 20px">
    <div class="oss-uploader">
      <input :id="id" type="file" @change="handleUpload">
      <label class="up" :for="id">选择文件</label>
    </div>
    <el-form-item label="文件名称" style="width: 600px;margin-top: 10px">
      <el-input v-model="resource.name"></el-input>
    </el-form-item>
    <div>
      <span style="margin-left: 10px">上传状态 : {{ status }}</span>
    </div>
  </div>
</template>

<script>
import {client} from "@/utils/oss.js";

export default {
  props: ["id", "filename", "type"],
  data() {
    return {
      resource: {
        type: 1,
        name: "",
        extensionName: "",
        linkId: ""
      },
      status: '未上传'
    }
  },
  methods: {
    handleUpload(e) {
      this.status = '准备上传';
      let f = e.target.files[0];
      this.resource.name = f.name
      switch (this.type) {
        case "ppt": {
          this.handlePPTUpload(f);
          break;
        }
        case "img": {
          this.handleImgUpload(f);
          break;
        }
        default:
          return;
      }

    },

    handleImgUpload(file) {
      client()
        .multipartUpload(Date.now().toString(), file)
        .then((result) => {
          let url = result.res.requestUrls[0];
          this.status = '上传成功，url：' + url;
          let i = url.indexOf('?');
          if (i < 0) {
            this.$emit("img", url);
          } else {
            this.$emit("img", url.slice(0, i + 1));
          }
        });
    },

    handlePPTUpload(file) {
      let that = this
      client()
        .multipartUpload((Date.now().toString() + file.name), file)
        .then((result) => {
          that.status = '上传完成';
          that.resource.linkId = result.res.requestUrls[0]
          that.$api.resource.saveResource(that.resource).then(res => {
            that.$emit('getResourceId', res.data)
          })
        });
    },

  },
};
</script>

<style>
.oss-uploader {
  cursor: pointer;
  line-height: 35px;
  width: fit-content;
  height: fit-content;
  color: white;
  background-color: rgb(0, 124, 248);
  padding: 3px 8px;
  border-radius: 10px;
  margin-left: 20px;
  margin-top: 20px;
}

.oss-uploader input {
  display: none;
}

.ppt,
.img,
.up {
  cursor: pointer;
  display: inline-block;
  line-height: 36px;
  font-size: 16px;
}
</style>
